﻿namespace Toggl.PhoneClient.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using ap2.Phone.Core.Data;
    using SilverlightPhoneDatabase;

    public class SilverlightDbSession : ISession
    {
        private Database database;

        public SilverlightDbSession(Database database)
        {
            this.database = database;
        }

        #region ISession Members

        public void CommitChanges()
        {
            this.database.Save();
        }

        public void Delete<T>(Func<T, bool> expression)
        {
            this.database.Table<T>().RemoveRange(expression);
        }

        public void Delete<T>(T item)
        {
            this.database.Table<T>().Remove(item);
        }

        public void DeleteAll<T>()
        {
            this.database.Table<T>().ToList().ForEach(item => this.database.Table<T>().Remove(item));
        }

        public T Single<T>(Func<T, bool> expression)
        {
            return this.database.Table<T>().Where(expression).FirstOrDefault();
        }

        public IEnumerable<T> All<T>()
        {
            return this.database.Table<T>().ToList();
        }

        public void Save<T>(T item)
        {
            this.database.Table<T>().Add(item);
        }

        public void Dispose()
        {
            this.database.Save();
            this.database = null;
        }

        #endregion
    }
}
